<?php
add_action('wp_head','insert_seo_meta');
function insert_seo_meta()
{
	global $post;
	global $paged;
	global $wp_query;
	$robots_content='noindex,nofollow';
	$title ='';
	$desc_content ='';
	$keys_content='';
	$html_tags = array("<p>", "</p>","\t","\n","\r","\0","\x0B");

	if ( is_tag())
	{
		$title = single_tag_title('',false) . ' - '. get_bloginfo('name');
		$cat = get_query_var('tag_id');
		
		$desc_content      = preg_replace( '|\[(.+?)\](.+?\[/\\1\])?|s', '',str_replace($html_tags, "", tag_description()));
		if(!$desc_content)
		{
			$desc_content = bt_general_term_des($cat);
		}
		
		if($cat)
		{
			$keys_content = bt_get_option_term_meta($cat);
			if(!$keys_content)
			{
				$keys_content = bt_general_term_keyword($cat);
			} 
		}
		
		$robots_content    = 'index,follow';
		
	}
	elseif (is_category() || is_tax() )
	{
		$cat = get_query_var('cat');
		$title= single_cat_title('',false);
		$desc_content      = preg_replace( '|\[(.+?)\](.+?\[/\\1\])?|s', '',str_replace($html_tags, "", category_description()));
		
		if(!$desc_content)
		{
			$desc_content = bt_general_term_des($cat);
		}
		
		if($cat)
		{
			$keys_content = bt_get_option_term_meta($cat);
			if(!$keys_content)
			{
				$keys_content = bt_general_term_keyword($cat);
			} 
		}
		$robots_content    = 'index,follow';
	}
	elseif (is_archive())
	{
		$robots_content     = 'noindex,follow';
		$desc_content      = get_option('seo_description');
		$keys_content      = get_option('seo_keywords');
		if(is_day())
		{
			$title = get_bloginfo('name') . ' - Ngày ' . get_the_date('j/m/Y');
		}
		elseif (is_month())
		{
			$title = get_bloginfo('name') . ' - Tháng ' . get_the_date('m/Y');
		}
		elseif (is_year())
		{
			$title = get_bloginfo('name') .  ' - Năm ' . get_the_date('Y');
		}
		elseif (is_author())
		{
			$title = get_bloginfo('name') . ' - Theo người đăng';
		}
		else
		{
			$title= single_cat_title('',false);
			$desc_content      = preg_replace( '|\[(.+?)\](.+?\[/\\1\])?|s', '',str_replace($html_tags, "", category_description()));
			$keys_content      = $desc_content;
			$robots_content    = 'index,follow';
		}

		 
	}
	elseif (is_search())
	{
		$title= 'Ket qua tim kiem tu '. $_GET['s'];
		$robots_content     = 'none';
		$desc_content      = $_GET['s'];
		$keys_content      = $_GET['s'];
	}
	elseif (is_single() || is_page() || is_page_template())
	{
		$title = get_post_meta($post->ID, "title", true);
		if(strlen($title)<5){$title=   the_title('','',false);}
		$robots_content     = 'index,follow';
		$desc_content       = get_post_meta($post->ID, "description", true);
		$keys_content       = get_post_meta($post->ID, "keywords", true);
		if(!$desc_content) $desc_content = bt_creat_desc();
		if(!$keys_content) $keys_content = bt_get_top_key($post->post_content);
	}
	elseif (is_404())
	{
		$title= 'Không tìm thấy - Lỗi 404';
		$robots_content     = 'noindex';
	}
	elseif (is_home()|| is_front_page())
	{
		$robots_content = 'index,follow';
		$title= get_option('seo_title');
		if(!$title)
			$title ="";
		$desc_content      = get_option('seo_description');
		$keys_content      = get_option('seo_keywords');
	}

	if ($paged>1)
	{
		$title .= ' - Trang '. $paged;
		$robots_content = 'noindex,follow';
	}

	echo '<meta name="robots" content="noodp,'.$robots_content.'" />';
	echo "\n";
	echo '<title>' . $title .  '</title>';
	echo "\n";
	echo '<meta name="keywords" content="'.$keys_content.'" />';
	echo "\n";
	echo '<meta name="description" content="'.$desc_content.'" />';
	echo "\n";
	echo '<meta name="author" content="'.get_bloginfo('home').'" />';
	echo "\n";

}

function add_nofollow_to_comments_popup_link(){
	return ' rel="nofollow" ';
}
add_filter( 'comments_popup_link_attributes', 'add_nofollow_to_comments_popup_link' );


function bt_creat_desc()
{
	global $post;
	global $paged;
	global $wp_query;
	
	// remove html
	$text = strip_tags($post->post_content);
	$clearText = str_replace("\r\n","",$text); 
	$des = $clearText; //bt_150_chars($clearText);
	if($des) update_post_meta($post->ID, 'description', $des);
	return $des;
}

function bt_get_top_key($content)
{
	global $post;
	global $paged;
	global $wp_query;
	
	$text = strip_tags($content);
	$normanText = strtolower($text);
	$arrayWord = preg_split("/[\s,.?!:;()-]+/u", $normanText);
	$keywords1char = get_top_word_in_array($arrayWord, 5);
	/* -- END 1 character -- */
	
	$i = 0;
	foreach ($arrayWord as $key => $val) {
		if($i == 0) {$temp = $val; 				$array2char[] = $temp2.' '.$val;}
		else {$array2char[] = "$temp $val"; 	$temp2 = $val;}
		$i++; if($i == 2) $i = 0;
	}
	$keywords2char = get_top_word_in_array($array2char, 10);
	/* -- END 2 character -- */
	
	$i = 0;
	foreach ($arrayWord as $key => $val) {
		if($i == 0) {$temp = $val; 					$array3char[] = "$temp2 $val";		$temp3 = "$temp3 $val"; }
		elseif($i == 1) {$temp = "$temp $val"; 		$temp2 = $val;						$array3char[] = "$temp3 $val"; }
		else {$array3char[] = "$temp $val"; 		$temp2 = "$temp2 $val"; 			$temp3 = $val; }
		$i++; if($i == 3) $i = 0;
	}
	$keywords3char = get_top_word_in_array($array3char, 6);
	/* -- END 3 character -- */
	
	$i = 0;
	foreach ($arrayWord as $key => $val) {
		if($i == 0) {$temp = $val; 					$array4char[] = "$temp2 $val";		$temp3 = "$temp3 $val"; 			$temp4 = "$temp4 $val"; }
		elseif($i == 1) {$temp = "$temp $val"; 		$temp2 = $val;						$array4char[] = "$temp3 $val";		$temp4 = "$temp4 $val"; }
		elseif($i == 2) {$temp = "$temp $val"; 		$temp2 = "$temp2 $val";				$temp3 = $val;						$array4char[] = "$temp4 $val"; }
		else {$array4char[] = "$temp $val"; 		$temp2 = "$temp2 $val"; 			$temp3 = "$temp3 $val";				$temp4 = $val; }
		$i++; if($i == 4) $i = 0;
	}
	$keywords4char = get_top_word_in_array($array4char, 4);
	/* -- END 3 character -- */
	
	$keywords = "$keywords1char, $keywords2char, $keywords3char, $keywords4char";
	if($keywords) update_post_meta($post->ID, 'keywords', $keywords);
	return $keywords;
}

function get_top_word_in_array($array, $number)
{	
	// count word
	$arrayCount = array_count_values($array);
	// sort word
	asort($arrayCount);
	$arrayCount = array_reverse($arrayCount);
	// get top word
	$i = 0;
	
		foreach ($arrayCount as $key => $val) {
			if(trim($key)) $keywords[] = $key;
			$i++; if($i == $number) break;
		}	
	return $keywords = @implode(', ', $keywords);
}

function bt_add_script_meta()
{
	echo '
	<style type="text/css">
		.bt_load_keyword,.bt_general_des{float:right;margin-right:17px}
	</style>
	<script type="text/javascript">
		jQuery(document).ready(function($) {
			$("textarea[name=description]").before(\'<a href="#" class="bt_general_des">General Description</a>\');
			$("textarea[name=keywords]").before(\'<a href="#" class="bt_load_keyword">General Keyword</a>\');
			
			$("a.bt_general_des").click(function(){
				var data = $("textarea[name=content]").val().replace(/(<.*?>)/ig,"").replace(/\n/g, "").substr(0, 150);
				$("textarea[name=description]").val(data);
				return false;
			});
			
			$("a.bt_load_keyword").click(function(){
				var data = $("textarea[name=content]").val();
				$.post(ajaxurl, {action: \'bt_get_top_key\', data: data}, function(response){
					if (response) {
						$("textarea[name=keywords]").val(response);
					}
					else {
						alert("Can not creat Keywords. Please check Post Content!");
					}
				});
				return false;
			});
		});
	</script>
	';
}
add_action('admin_head-post.php', 'bt_add_script_meta');
add_action('admin_head-post-new.php', 'bt_add_script_meta');

function bt_load_keyword_callback()
{
	$data = $_POST['data'];
	if($data)
	{
		$keywords =  bt_get_top_key($data);
		if($keywords) echo $keywords;
	}
	die();
}
add_action('wp_ajax_bt_get_top_key', 'bt_load_keyword_callback');

function bt_get_option_term_meta($id)
{
	$meta = get_option('meta_term');
	if (empty($meta)) $meta = array();
	if (!is_array($meta)) $meta = (array) $meta;
	$meta = isset($meta[$id]) ? $meta[$id] : array();
	$value = $meta['keywords'];
	return $value;
}

function bt_general_term_keyword($id)
{
	$query = new WP_Query('posts_per_page=10&term='.$id);
	$keywords = '';
	while ( $query->have_posts() ) : $query->the_post();
		$keywords .= get_the_excerpt();
	endwhile;
	$keywords = bt_get_top_key($keywords);
	return $keywords;
}

function bt_general_term_des($id)
{
	$query = new WP_Query('posts_per_page=10&term='.$id);
	$des = '';
	while ( $query->have_posts() ) : $query->the_post();
		$des .= get_the_title(). ', ';
	endwhile;
	//$des = bt_150_chars($des);
	return $des;
}